<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */

namespace App\Support\Traits;

use RuntimeException;

use function Hyperf\Config\config;

trait AesUtil
{
    // public const key = 'tamgoworldaeskey';
    // public const iv = 'tamgoworldaeskey';

    public static function encrypt($data)
    {
        $data = is_string($data) ? $data : json_encode($data);
        return openssl_encrypt($data, 'AES-128-CBC', static::getKey(), 0, static::getIv());
    }

    public static function decrypt(string $data)
    {
        $decryptedData = openssl_decrypt($data, 'AES-128-CBC', static::getKey(), 0, static::getIv());
        if ($decryptedData === false) {
            throw new RuntimeException('decrypted failure');
        }
        return $decryptedData;
    }

    private static function getKey(): string
    {
        return config('aes.key', 'KEY6747ED05BB920');
    }

    private static function getIv(): string
    {
        return config('aes.iv', 'IV_6747ED4470D67');
    }
}
